﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using WooCoo.ObjectModel;
using WooCoo.ObjectModel.ManagedProperty;

namespace WooCoo.Extension
{
    public static class ADOExtension
    {
        /// <summary>
        /// 将IDataReader数据转换成指定的实体对象列表
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="dataSource"></param>
        /// <param name="entityNum">小于等于0，则返回所有数据</param>
        /// <returns></returns>
        public static IList<TResult> ToEntityList<TResult>(this IDataReader reader, int entityNum = -1)
            where TResult : Entity, new()
        {
            //数据初始化
            IList<TResult> result = new List<TResult>();
            ToEntityList(reader, result, entityNum);            
            return result;
        }

        public static void ToEntityList<TResult>(this IDataReader reader, IList<TResult> targetList, int entityNum = -1)
            where TResult : Entity, new()
        {
            //数据源判断
            if (reader == null || reader.IsClosed)
            {
                //TODO:返回值初始化
                targetList = new List<TResult>();
            }

            var returnEntitys = entityNum > 0 ? entityNum : int.MaxValue;

            if (reader.Read())
            {
                var rowsIndex = 0;
                do
                {
                    rowsIndex += 1;
                    var entity = new TResult();
                    (entity as ITrackStatus).MarkClean();
                    entity.ValidationRules.BrokenRules.Clear();
                    IPropertyInfo pInfo;
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        pInfo = entity.Properties.GetProperties().FirstOrDefault(op => op.FriendlyName == reader.GetName(i));
                        if (pInfo != null && !(reader[i] is DBNull))
                        {
                            if (pInfo.Type == typeof(bool))
                            {
                                entity.LoadProperty(pInfo, reader[i].ToBool());
                            }
                            else
                                entity.LoadProperty(pInfo, reader[i]);
                        }
                    }
                    targetList.Add(entity);
                } while (reader.Read() && rowsIndex < returnEntitys);
            }
        }

    }
}
